<template>
  <div class="permission-list">
    <h1 class="page-title">权限管理页面</h1>
    <div class="table-container">
      <!-- 添加按钮和搜索框 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-button type="primary" @click="showAddForm">添加权限</el-button>
        <div>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入权限名称"
            style="width: 250px; margin-right: 10px;"
            clearable
            @clear="searchPermissions"
            @keyup.enter="searchPermissions"
          />
          <el-button type="primary" @click="searchPermissions">搜索</el-button>
        </div>
      </div>

      <el-table :data="permissionList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="主键ID" width="80" />
        <el-table-column prop="permissionName" label="权限名称" width="150" />
        <el-table-column prop="permissionCode" label="权限编码" width="150" />
        <el-table-column prop="type" label="权限类型" width="150">
          <template #default="scope">
            <span v-if="scope.row.type === 0">菜单</span>
            <span v-else-if="scope.row.type === 1">按钮</span>
            <span v-else-if="scope.row.type === 2">接口</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="资源路径" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button
              size="small"
              @click="editPermission(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deletePermission(scope.row)"
              :disabled="scope.row.status === 2">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加权限表单对话框 -->
    <el-dialog title="添加权限" v-model="addFormVisible" width="500px">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="addForm.permissionName"></el-input>
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input v-model="addForm.permissionCode"></el-input>
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" :value="0"></el-option>
            <el-option label="按钮" :value="1"></el-option>
            <el-option label="接口" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源路径" prop="url">
          <el-input v-model="addForm.url"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="禁用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="addForm.createTime"
            type="datetime"
            placeholder="请选择创建时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="addForm.updateTime"
            type="datetime"
            placeholder="请选择更新时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑权限表单对话框 -->
    <el-dialog title="编辑权限" v-model="editFormVisible" width="500px">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="editForm.permissionName"></el-input>
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input v-model="editForm.permissionCode"></el-input>
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" :value="0"></el-option>
            <el-option label="按钮" :value="1"></el-option>
            <el-option label="接口" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源路径" prop="url">
          <el-input v-model="editForm.url"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="禁用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="editForm.createTime"
            type="datetime"
            placeholder="请选择创建时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="editForm.updateTime"
            type="datetime"
            placeholder="请选择更新时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionListAPI, addPermissionAPI, updatePermissionStatusAPI, deletePermissionAPI, updatePermissionAPI, listByNameAPI } from '@/apis/sys'

export default {
  name: 'PermissionList',
  data() {
    return {
      permissionList: [],
      allPermissionList: [], // 保存所有权限数据
      searchKeyword: '', // 搜索关键词
      loading: false,
      // 添加表单相关数据
      addFormVisible: false,
      addForm: {
        permissionName: '',
        permissionCode: '',
        type: 0,
        url: '',
        status: 1,
        createTime: '',
        updateTime: ''
      },
      addFormRules: {
        permissionName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        permissionCode: [
          { required: true, message: '请输入权限编码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择权限类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 编辑表单相关数据
      editFormVisible: false,
      editForm: {
        id: null,
        permissionName: '',
        permissionCode: '',
        type: 0,
        url: '',
        status: 1,
        createTime: '',
        updateTime: ''
      },
      editFormRules: {
        permissionName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        permissionCode: [
          { required: true, message: '请输入权限编码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择权限类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
    }
  },
  async mounted() {
    await this.fetchPermissionList()
  },
  methods: {
    // 搜索权限
    async searchPermissions() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，则显示所有权限
        await this.fetchPermissionList();
        return;
      }

      // 调用后端接口进行搜索
      this.loading = true;
      try {
        const res = await listByNameAPI({
          permissionName: this.searchKeyword.trim()
        });
        if (res.code === 0) {
          this.permissionList = res.data.map(permission => {
            return {
              ...permission,
              createTime: permission.createTime || '-',
              updateTime: permission.updateTime || '-'
            }
          })
          // 同时更新完整权限列表
          this.allPermissionList = [...this.permissionList];
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取权限列表失败'
          })
        }
      } catch (error) {
        console.error('搜索权限失败:', error);
        this.$message({
          type: 'error',
          message: '搜索权限失败: ' + (error.msg || error.message || '未知错误')
        });
      } finally {
        this.loading = false;
      }
    },

    async fetchPermissionList() {
      this.loading = true
      try {
        const res = await getPermissionListAPI()
        if (res.code === 0) {
          const formattedPermissions = res.data.map(permission => {
            return {
              ...permission,
              createTime: permission.createTime || '-',
              updateTime: permission.updateTime || '-'
            }
          })
          this.allPermissionList = formattedPermissions
          this.permissionList = [...formattedPermissions]
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取权限列表失败'
          })
        }
      } catch (error) {
        console.error('获取权限列表失败:', error)
        this.$message({
          type: 'error',
          message: '获取权限列表失败: ' + (error.msg || error.message || '未知错误')
        })
      } finally {
        this.loading = false
      }
    },
    getStatusType(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'info'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '禁用'
        case 1:
          return '启用'
        case 2:
          return '删除'
        default:
          return '未知'
      }
    },
    async toggleStatus(row) {
      try {
        const requestData = {
          id: row.id,
          status: row.status === 1 ? 0 : 1 // 切换状态：启用(1) <-> 禁用(0)
        };

        const res = await updatePermissionStatusAPI(requestData);

        if (res.code === 0) {
          // 更新成功后重新获取权限列表
          await this.fetchPermissionList();

          this.$message({
            type: 'success',
            message: '状态更新成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '状态更新失败'
          });
        }
      } catch (error) {
        console.error('状态更新失败:', error);
        this.$message({
          type: 'error',
          message: '状态更新失败: ' + (error.msg || error.message || '未知错误')
        });
      }
    },
    async deletePermission(row) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const requestData = {
            id: row.id
          };

          const res = await deletePermissionAPI(requestData);

          if (res.code === 0) {
            // 删除成功后重新获取权限列表
            await this.fetchPermissionList();

            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.msg || '删除失败'
            });
          }
        } catch (error) {
          console.error('删除失败:', error);
          this.$message({
            type: 'error',
            message: '删除失败: ' + (error.msg || error.message || '未知错误')
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 显示添加表单
    showAddForm() {
      this.addFormVisible = true
      // 重置表单数据
      this.addForm = {
        permissionName: '',
        permissionCode: '',
        type: 0,
        url: '',
        status: 1,
        createTime: '',
        updateTime: ''
      }
    },
    cancelAdd() {
      this.addFormVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 确认添加
    confirmAdd() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await addPermissionAPI(this.addForm)
            
            if (res.code === 0) {
              // 添加成功后重新获取权限列表
              await this.fetchPermissionList()
              
              this.$message({
                type: 'success',
                message: '权限添加成功!'
              })
              this.addFormVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '权限添加失败'
              })
            }
          } catch (error) {
            console.error('添加权限失败:', error)
            this.$message({
              type: 'error',
              message: '添加权限失败: ' + (error.msg || error.message || '未知错误')
            })
          }
        }
      })
    },
    // 显示编辑表单
    editPermission(row) {
      this.editFormVisible = true
      // 初始化表单数据
      this.editForm = {
        id: row.id,
        permissionName: row.permissionName,
        permissionCode: row.permissionCode,
        type: row.type,
        url: row.url,
        status: row.status,
        createTime: row.createTime,
        updateTime: row.updateTime
      }
    },

    // 取消编辑
    cancelEdit() {
      this.editFormVisible = false
      this.$refs.editFormRef.resetFields()
    },

    // 确认编辑
    confirmEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updatePermissionAPI(this.editForm)
            
            if (res.code === 0) {
              // 更新成功后重新获取权限列表
              await this.fetchPermissionList()
              
              this.$message({
                type: 'success',
                message: '权限更新成功!'
              })
              this.editFormVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '权限更新失败'
              })
            }
          } catch (error) {
            console.error('更新权限失败:', error)
            this.$message({
              type: 'error',
              message: '更新权限失败: ' + (error.msg || error.message || '未知错误')
            })
          }
        }
      })
    },
  }
}
</script>

<style scoped>
.permission-list {
  padding: 20px;
  background-color: #f5f5f5;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
}
</style>